无法运行基于TKinter

时间:2016-07-19 02:53:28

标签: python tkinter

import Tkinter as tk
from functools import partial

pad = [[1, 2, 3], [4, 5, 6], [7, 8, 9], ["C", 0, "S"]]
passcode = ""

def append_passcode(value):
    global passcode
    if len(passcode) == 4:
        passcode = passcode[1:]
    passcode += value

def clear():
    global passcode
    passcode = ""

def submit():
    global passcode
    if passcode == "1234":
        msgBox.showinfo("Login Attempt", "Successful")
        passcode = ""
    else:
        msgBox.showinfo("Login Attempt", "Failed")
        passcode = ""

main_window = tk.Tk()

btns = []
row_placement = 0
for line in pad:
    col_placement = 0
    for number in line:
        btn_command = partial(append_passcode, str(number))
        btn = tk.Button(main_window, text=str(number), width=10, command=btn_command)
        btns.append(btn)
        btn.grid(row=row_placement, column=col_placement)
        col_placement += 1
    row_placement += 1

#Setting C to clear the passcode function
btns[-3].config(command=clear)

#Setting S to submit passcode
btns[-1].config(command=submit)

我正在编写一个小键盘应用程序,用户必须输入正确的4位数代码才能访问应用程序。当测试代码运行时,GUI不会出现。要使此代码正常运行需要做些什么?

1 个答案:

答案 0 :(得分:1)

这是你做错了什么:

  • 拼错的tkinter
  • 不包括

    main_window.mainloop()
    

试试此代码

import tkinter as tk
from functools import partial

pad = [[1, 2, 3], [4, 5, 6], [7, 8, 9], ["C", 0, "S"]]
passcode = ""

def append_passcode(value):
    global passcode
    if len(passcode) == 4:
        passcode = passcode[1:]
    passcode += value

def clear():
    global passcode
    passcode = ""

def submit():
    global passcode
    if passcode == "1234":
        msgBox.showinfo("Login Attempt", "Successful")
        passcode = ""
    else:
        msgBox.showinfo("Login Attempt", "Failed")
        passcode = ""

main_window = tk.Tk()

btns = []
row_placement = 0
for line in pad:
    col_placement = 0
    for number in line:
        btn_command = partial(append_passcode, str(number))
        btn = tk.Button(main_window, text=str(number), width=10, command=btn_command)
        btns.append(btn)
        btn.grid(row=row_placement, column=col_placement)
        col_placement += 1
    row_placement += 1

#Setting C to clear the passcode function
btns[-3].config(command=clear)

#Setting S to submit passcode
btns[-1].config(command=submit)

main_window.mainloop()

现在你的窗口应该出现了。

希望这有帮助,并随时评论任何问题。