【问题标题】:Can this be done more than once?可以多次这样做吗?
【发布时间】:2017-11-30 19:20:57
【问题描述】:
from tkinter import *
from tkinter import ttk
import webbrowser
import urllib

root = Tk()
 w = Label(root, text="Where can I take you?")
 w.pack()

url = 'http://sampdm.net/member.php?action=profile&uid=1'
def Openurl(url):
webbrowser.open_new(url)

button = Button(root, text = "Open Owners Profile #1", command = lambda: 
Openurl(url))

button.pack()
root.mainloop()

有没有办法用另一个类似的链接制作另一个按钮? 我知道会有,但我似乎无法弄清楚

【问题讨论】:

  • 你需要先修复你的代码缩进!也可以在帖子中标记tkinter
  • 你需要缩进Openurl()下面的行。
  • 是什么阻止您创建另一个具有不同 URL 的按钮?您不知道如何在父级上打包多个小部件吗?
  • 实际上,FamousJamoues 我没有。呵呵xd
  • hRdCoder 是缩进的。它只在线程中

标签: python tkinter


【解决方案1】:

通过阅读 cmets,您似乎不确定如何在 Tkinter 窗口中创建多个按钮。

这真的很简单,您只需重复创建第一个按钮的过程即可。

我将提供 2 个示例。

您可以通过以下方式为您希望为其提供按钮的每个网站手动创建每个按钮。

from tkinter import *
import webbrowser


root = Tk()

url = 'http://sampdm.net/member.php?action=profile&uid=1'
url2 = 'www.google.com' # assign any variable name you want.
some_other_url = 'https://www.yahoo.com/'

def Openurl(url):
    webbrowser.open_new(url)

w = Label(root, text="Where can I take you?")
w.pack()

# Here you can keep creating buttons using the same method as the first button.
# Just make sure you assign the correct url variable to the command.
button = Button(root, text = "Open Owners Profile #1", command = lambda: Openurl(url)).pack()
button2 = Button(root, text = "Open Google", command = lambda: Openurl(url2)).pack()
some_other_button = Button(root, text = "Open something else", command = lambda: Openurl(some_other_url)).pack()

root.mainloop()

这是一个从列表创建按钮的示例。这是一个简单的例子,但应该足以说明它是如何完成的。

from tkinter import *
import webbrowser


root = Tk()

# Here we create a list to use in button creation.
url_list = ['www.google.com', 'www.yahoo.com']

w = Label(root, text="Where can I take you?")
w.pack()

def Openurl(url):
    webbrowser.open_new(url)

def create_buttons():
    for url in url_list: # for each string in our url list
        # creating buttons from our for loop values that will pack
        # in the order they are created.
        Button(root, text = url, command = lambda u = url: Openurl(u)).pack()

create_buttons()

root.mainloop()

【讨论】:

    猜你喜欢
    • 2012-02-19
    • 1970-01-01
    • 1970-01-01
    • 2015-11-19
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 2016-12-07
    • 2014-03-27
    相关资源
    最近更新 更多