Python, Tkinter, StringVar



论坛晚上好。让我从你那里得到帮助。我需要将键从字典输出到终端,我通过GUI Tkinter和tk.StringVar进行工作。例如,有一对"苹果"one_answers"菠萝",因为"苹果"这个词的拼写错误,我把"菠萝"敲掉了。请帮助。下面的代码!真诚,俄罗斯!

from tkinter import *
import tkinter as tk
window = tk.Tk()
window.title('Boom')
window.geometry('300x200+50+75')
window.resizable(True, True)
def info():
print(info)
fruit = {'яблоко':'apple', "ананас":'pineapple'}
mystring = tk.StringVar(window)
def getvalue():
print(mystring.get())
entry = tk.Entry(window, textvariable=mystring, bg='white', fg='black', width=200).pack()
button = tk.Button(window, 
text='Translate',
bg='blue',
fg='black', width=15, height=3, command=getvalue).pack()
my_string1 = tk.StringVar(window)
def info():
print(my_string1())
entry = tk.Entry(window, textvariable=my_string1, bg='white', fg='black', width=200).pack()
window.mainloop()

下面是俄语和英语相互翻译的代码:

import tkinter as tk
window = tk.Tk()
window.title('Boom')
window.geometry('300x200+50+75')
window.resizable(True, True)
# Create two dictionaries: one for Russian to English, the other for English to Russian
fruit_r_to_e = {'яблоко':'apple', "ананас":'pineapple'}
fruit_e_to_r = {english: russian for russian, english in fruit_r_to_e.items()}
mystring = tk.StringVar(window)
my_string1 = tk.StringVar(window)
def getvalue():
global mystring, my_string1, fruit_e_to_r, fruit_r_to_e
string = mystring.get()
# If the string is in English, translate it to Russian
if string in fruit_e_to_r:
print(fruit_e_to_r[string])
# If the string is in Russian, translate it to English
elif string in fruit_r_to_e:
print(fruit_r_to_e[string])
else:
print("This word is not in the dictionary.")
def info():
global my_string1
print(my_string1())
entry = tk.Entry(window, textvariable=mystring, bg='white', fg='black', width=200)
entry.pack()
button = tk.Button(window, 
text='Translate',
bg='blue',
fg='black',
width=15,
height=3,
command=getvalue
)
button.pack()
entry = tk.Entry(window, textvariable=my_string1, bg='white', fg='black', width=200)
entry.pack()
window.mainloop()

我创建了两个字典,每个方向对应一个翻译。当调用getvalue()时,它检查单词是否在英语字典中:if string in fruit_e_to_r:,如果在,则将其翻译为俄语。如果不是,它检查它是否在俄语词典:elif string in fruit_r_to_e:中,如果是,它将其翻译成英语。如果它不在两个字典中:else:,它显示一条消息,说这个词不在两个字典中。

我还对代码做了一些其他更改。我删除了from tkinter import *,因为您已经在下一行导入了tkinter:import tkinter as tk,并且因为不鼓励通配符导入(使用from <package> import *)。

我还注意到,当您创建小部件时,当您将小部件分配给变量时调用.pack(),例如您使用entry = tk.Entry(...).pack()。这是一个问题,因为pack()方法返回None,因此您将无法在稍后的程序中使用小部件。您需要呼叫entry = tk.Entry(...),然后在下一行呼叫entry.pack()。这样,entry变量实际上包含了tkinter.Entry的实例,而不是None

您会注意到我还在函数中使用了global语句。这不是必需的(除非您要分配变量),但这通常是一个好主意。global告诉函数它正在使用在函数之外定义的变量。因此,global mystring, fruit_e_to_r, fruit_r_to_e告诉getvalue(),mystringfruit_e_to_rfruit_r_to_e都是在getvalue()之外创建的变量。

最新更新