如何使用Tkinker创建字母计数器?

2024-09-27 07:28:27 发布

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

我刚开始学习Python,我正试图创建一个矿物计数器,只使用微观岩相学中的字母,但我在将Python代码传递给Tkinker时遇到了问题。你们能给我一些关于如何让我的成果发挥作用的建议吗?我发现即使在在线教程中使用get()方法也很有挑战性

你们能教这个noob吗?谢谢大家!

我的原始代码:

# define sample
sample = "qreqqwer"

# mineral q:
mineralq= "q"

countq = sample.count(mineralq)

# print count of q
print("The quantity of q is: ", countq)

我用Tkinker制作的结构:

from tkinter import *
import tkinter as tk

# Window
window=tk.Tk()
window.title("Mineral Counter")
window.geometry("800x1000")
window.configure(bg="#00090F")

inputUser=tk.Text(window,width=225,height=5,font=("Arial bold",12),wrap="word", bg="#00090F", fg="white")
inputUser.pack()

# define sample

# mineral q:


countq = inputUser.count("q")

# print count of q
output.insert(tk.INSERT,countq)
output=tk.Text(window,width=20,height=2,font=("Arial bold",12), bg="#00090F", fg="white")
output.pack()

window.mainloop()

Tags: ofsample代码outputcountwindowtkbg
1条回答
网友
1楼 · 发布于 2024-09-27 07:28:27

您需要一个按钮来更新代码,因为最初Text框是空的,因此q没有出现,因此无法插入任何内容

试试这个:

首先创建一个按钮,该按钮具有在输入数据后单击的功能

b = tk.Button(window, text='Click Me', command=click)
b.pack()

现在定义单击按钮时调用的函数

def click():
    sample = inputUser.get('1.0', 'end-1c') #getting value from text box 1
    mineralq = 'q' #letter to be counted
    countq = sample.count(mineralq) #counting the letter
    output.insert('1.0', f'The quantity of q is: {countq}') #inserting the output to text box 2

希望它消除您的疑虑,如果有任何错误,请告诉我

干杯

相关问题 更多 >

    热门问题