使输入和ifels匹配

2024-04-26 20:45:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我这里有我的剧本

from tkinter import *
from tkinter import messagebox
import commands

db=''

def launch():
        # Database Check.
            if db.lower() == 'y':
                commands.db_download()
            else:
                db.lower() == 'n'



root = Tk()


checklabel = Label(root, text="Check for new databases? Y/N: ")
checkentree = Entry(root, textvariable=db)
checkbutton = Button(root, text="Go", command=launch)


checklabel.pack()
checkentree.pack()
checkbutton.pack()


root.mainloop()

一切正常,除了匹配的部分。 当我在输入框中输入“y”或“n”,甚至任何其他内容并单击“Go”时,什么都不会发生。。。为什么什么都没发生?我怎样才能让它工作呢?你知道吗


Tags: textfromimportgodbtkintercheckroot
2条回答

有一个改变,你需要作出和一对夫妇,这是一个好主意。你知道吗

第一,“需要”改变:

在tkinter小部件中使用textvaraible时,必须使用其中一个objectvar(即:StringVar、IntVar等等)。还要记住,您需要在db上使用.get(),因为get()方法是从ObjectVar获取值的方法。你知道吗

要完成此更改,请执行以下操作:

db = ''

def launch():
    if db.lower() == 'y':

对此:

db = tk.StringVar()
db.set('') # not actually required in this instance but still good to know how to set the value of a ObjectVar.

def launch():
    if db.get().lower() == 'y':

以及将您的dbtkinter代码移过root,否则StringVar将抛出这个错误AttributeError: 'NoneType' object has no attribute '_root',因为您还没有启动StringVar要锁定的tk实例。你知道吗

也就是说,你应该改变你导入tkinter的方式,或者清理你的小部件名称和打包方式。你知道吗

最好是import tkinter as tk而不是from tkinter import *,因为这有助于防止意外地从其他导入或您自己的变量/函数/类名覆盖导入。要使用这个新的导入方法,您只需要为每个方法/小部件使用前缀tk.。你知道吗

如果您不打算修改一个小部件(例如:永久性标签、按钮等),您不需要将其分配给变量,只需直接在小部件上使用您的几何管理器(在本例中是pack())。你知道吗

最后,您的if/else语句并不完全正确。它将起作用,但这一行db.lower() == 'n'没有做你认为它在做的事情。else语句没有任何要满足的条件。它只是if/elif/else语句中的最后一个选项,如果其他条件都不满足,它将运行。也就是说,如果你什么都不想做,如果其他条件都不满足,你可以简单地删除逻辑语句的else部分。你知道吗

请看下面的代码:

import tkinter as tk


def launch():
if db.get().lower() == 'y':
    print('commands.db_download()')
else:
    print('not y')   


root = tk.Tk()
db = tk.StringVar()
db.set('')

tk.Label(root, text="Check for new databases? Y/N: ").pack()
tk.Entry(root, textvariable=db).pack()
tk.Button(root, text="Go", command=launch).pack()

root.mainloop()
checkentree = Entry(root, textvariable=db)

textvariable参数应该是StringVar。但是db是一个字符串,而不是StringVar。
尝试传递StringVar。你知道吗

from tkinter import *
from tkinter import messagebox
import commands

def launch():
        # Database Check.
            if db.get().lower() == 'y':
                commands.db_download()
            #don't actually need these following lines because they don't do anything
            #else:
            #    #db.get().lower() == 'n'


root = Tk()
db=StringVar()


checklabel = Label(root, text="Check for new databases? Y/N: ")
checkentree = Entry(root, textvariable=db)
checkbutton = Button(root, text="Go", command=launch)


checklabel.pack()
checkentree.pack()
checkbutton.pack()


root.mainloop()

相关问题 更多 >