簡體   English   中英

Tkinter 和 Entry.get() 有問題

[英]having problems with Tkinter and Entry.get()

我需要幫助

我一直試圖在 python 中制作一個計算器程序,我做得很好。

我想使用相同的代碼和 Tkinter 庫為它制作一個 window 但它讓我很困惑。

我的計算器代碼是:

while True:

    num1 = 0
    num2 = 0
    num3 = 0
    
    print("Enter your calculation:")
    calc_in = str(input()).split()
    
    try:
        num1 = int(calc_in[0])
        op1 = calc_in[1]
        num2 = int(calc_in[2])
    except:
        print("Error: Make sure you typed your sum correctly")
        continue
        
    try:
        op2 = calc_in[3]
        num3 = int(calc_in[4])
    except:
        pass
    
    if op1 == "+":
        answer = num1 + num2
    elif op1 == "-":
        answer = num1 - num2
    elif op1 == "*":
        answer = num1 * num2
    elif op1 == "/":
        answer = num1 / num2
    
    try:
        if op2 == "+":
            answer = answer + num3
        elif op2 == "-":
            answer = answer - num3
        elif op2 == "*":
            answer = answer * num3
        elif op2 == "/":
            answer = answer / num3
    except:
        pass
    
    print(answer)

代碼工作正常,但是當我嘗試使用一個入口小部件進行修補時,它給我帶來了一些奇怪的東西。

到目前為止,這是 Tkinter 的代碼(我還沒有 tkinter output 位,因為我想看看它是否真的有效):

import tkinter as tk
import tkinter.ttk as ttk

window = tk.Tk()

label = tk.Label(
    text="Calculator",
    foreground="white",
    background="dodgerBlue",
    width=15,
    height=0,
    font=("Arial", 25),
)
label.pack()

calc_input = tk.Entry(
    foreground="dodgerBlue",
    background="white",
    width=15,
    font=("Arial", 25),
)
calc_input.pack()

window.mainloop()

while True:
    num1 = 0
    num2 = 0
    num3 = 0

    convert = str(calc_input.get)
    
    calc_in = convert.split()
    
    print(calc_in)
    break

    try:
        num1 = int(calc_in[0])
        op1 = calc_in[1]
        num2 = int(calc_in[2])
    except:
        print("Error: Make sure you typed your sum correctly")
        continue
        
    try:
        op2 = calc_in[3]
        num3 = int(calc_in[4])
    except:
        pass
    
    if op1 == "+":
        answer = num1 + num2
    elif op1 == "-":
        answer = num1 - num2
    elif op1 == "*":
        answer = num1 * num2
    elif op1 == "/":
        answer = num1 / num2
    
    try:
        if op2 == "+":
            answer = answer + num3
        elif op2 == "-":
            answer = answer - num3
        elif op2 == "*":
            answer = answer * num3
        elif op2 == "/":
            answer = answer / num3
    except:
        pass
    
    print(answer)

當我單擊輸入時,什么也沒有發生,但是當我關閉 window 時,我得到一個奇怪的數組:

['<bound', 'method', 'Entry.get', 'of', '<tkinter.Entry', 'object', '.!entry>>']

我不明白發生了什么,所以任何幫助將不勝感激。

您的代碼有兩個主要問題。

  1. 第一: calc_input.get這行代碼是錯誤的,因為你沒有在需要使用這個calc_input.get()的地方調用function
  2. 第二:在calc_input.get()這行代碼之后你得到一個錯誤_tkinter.TclError: invalid command name ".!entry"因為你在window被銷毀后試圖從輸入框中獲取值。

格式化代碼在這里

import tkinter as tk
import tkinter.ttk as ttk
convert = 0
window = tk.Tk()

label = tk.Label(
    text="Calculator",
    foreground="white",
    background="dodgerBlue",
    width=15,
    height=0,
    font=("Arial", 25),
)
label.pack()

calc_input = tk.Entry(
    foreground="dodgerBlue",
    background="white",
    width=15,
    font=("Arial", 25),
)
calc_input.pack()
def on_closing():
    global convert # Exccess to the global variable which  is define in line 3.
    convert = calc_input.get() # set the value to convert
    window.destroy() # destroy the window
    
window.protocol('WM_DELETE_WINDOW',on_closing) # This is execute when someone try to exit or destroy the window And call the on_closing function

window.mainloop()

while True:
    num1 = 0
    num2 = 0
    num3 = 0

    
    calc_in = convert.split()
    
    print(calc_in)
    break

    try:
        num1 = int(calc_in[0])
        op1 = calc_in[1]
        num2 = int(calc_in[2])
    except:
        print("Error: Make sure you typed your sum correctly")
        continue
    
        
    try:
        op2 = calc_in[3]
        num3 = int(calc_in[4])
    except:
        pass
    
    if op1 == "+":
        answer = num1 + num2
    elif op1 == "-":
        answer = num1 - num2
    elif op1 == "*":
        answer = num1 * num2
    elif op1 == "/":
        answer = num1 / num2
    
    try:
        if op2 == "+":
            answer = answer + num3
        elif op2 == "-":
            answer = answer - num3
        elif op2 == "*":
            answer = answer * num3
        elif op2 == "/":
            answer = answer / num3
    except:
        pass
    
    print(answer)

我昨天解決了同樣的問題你可以看看鏈接

您必須記住在每個 GUI 應用程序中,您應該做的所有事情都必須在您的 mainloop() 之前(或內部),因為這是 GUI 應用程序的本質,它們是一個循環並檢查應用程序的 state。

我看了你的代碼,發現了很多錯誤:

在 mainloop() function 之后你寫了一些代碼(While 循環)。 mainloop() 之后的每個代碼都將在您關閉 window 后執行,您應該記住,在您關閉 window 后,小部件將被銷毀。所以這就是為什么我要說你必須在 mainloop() 中擁有你想要的一切function。

如果你想得到你的條目值,你可以添加一個按鈕,通過點擊按鈕你可以打印條目的值。 (當然要看Button中command屬性的說明)

請記住,每個小部件都必須將根(或您在代碼中編寫的 window)作為第一個參數。 例如標簽(窗口,“這是標簽”)。

最后:在 while 循環中,當您編寫 break 命令時,代碼的 rest 永遠不會被執行。 所以所有那些 try except 塊,永遠不會被執行。

這是我用您的小部件樣式為您編寫的示例:

class MainWindow(tk.Tk):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.label = tk.Label(self,
                          text="Calculator",
                          foreground="white",
                          background="dodgerBlue",
                          width=15,
                          height=0,
                          font=("Arial", 25),
                          )
        self.label.pack()

        self.entry = tk.Entry(self,
                          foreground="dodgerBlue",
                          background="white",
                          width=15,
                          font=("Arial", 25),)
        self.entry.pack()

        self.button = tk.Button(self, text="Print Value",
                            command=self.print_entry_value)
        self.button.pack()

        self.mainloop()

    def print_entry_value(self) -> None:
        """
        This widget will print the entry value
        """

        value = self.entry.get()
        print(value)


if __name__ == "__main__":
    window = MainWindow()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM