如何在tkinter python的TopLevel窗口中放置按钮?

时间:2018-07-12 06:06:01

标签: python-2.7 tkinter toplevel

我有两个屏幕:window(子级)和root(主级) 我试图在通过方法command()创建的“窗口”屏幕上放置一个按钮。我已经编写了这段代码。

from tkinter import *

root = Tk()
def writeText():
    print "hello"
def command():
    window=Toplevel(root)
    Button(window,text="Button2",command=writeText).grid()
    Label(window,text="hello").grid()

button = Button(root, text="New Window", command=command)
button.grid()

root.mainloop()

但是此按钮2没有出现在第二个屏幕上。同时,标签出现在此屏幕上。然后控件进入writeText()函数。

当我从窗口屏幕的“按钮”中删除命令参数时,按钮就会出现。

有人可以帮我吗?

2 个答案:

答案 0 :(得分:1)

你们曾经尝试过在Toplevel上使用图像按钮吗?似乎在Toplevel上的以下代码不起作用(提示Windows)。根级别还可以。

tp = Toplevel()
tp.geometry("400x400")

btnphotoAdd=PhotoImage(file="32adduser.png")
btnAdd = Button(tp, text="Add User", font="Helvetica 20 bold", image=btnphotoAdd,compound=TOP)
btnAdd.grid(row=10, column=0, sticky=W)

答案 1 :(得分:0)

这是我的建议。

根据您的问题,您已放入from tkinter import *,但是在标签中却放入了Python 2.7。这是矛盾的,因为在Python 3.x中使用了tkinter(全部小写),而在Python 2.x中应使用Tkinter。也就是说,请尝试先修复导入。如果实际上使用的是Python 3,则需要更正打印语句以包含方括号。 print("hello")

2nd我将尝试更紧密地遵循PEP8,但是在这种情况下,我看不到任何会引起此问题的异常情况。

以下面的示例为例,让我知道您是否仍然遇到相同的问题。

Python 2.x示例:

import Tkinter as tk # Upper case T in Tkinter for Python 2.x


root = tk.Tk()

def write_text():
    print "hello"

def command():
    window = tk.Toplevel(root)
    tk.Button(window,text="Button2",command=write_text).grid()
    tk.Label(window,text="hello").grid()

button = tk.Button(root, text="New Window", command=command)
button.grid()

root.mainloop()

Python 3.x示例:

import tkinter as tk # all lowercase tkinter for Python 3.x


root = tk.Tk()

def write_text():
    print("hello") # Python 3.x requires brackets for print statements.

def command():
    window = tk.Toplevel(root)
    tk.Button(window,text="Button2",command=write_text).grid()
    tk.Label(window,text="hello").grid()

button = tk.Button(root, text="New Window", command=command)
button.grid()

root.mainloop()

如果仍然有问题,能否告诉我您使用的是Windows,Linux还是Mac?

相关问题