首页 > 解决方案 > 如何使用 Tkinker 创建一个字母计数器?

问题描述

我刚开始学习 Python,我正试图通过仅使用字母进行显微岩相学来创建矿物计数器,但是我在将我的 Python 代码传递给 Tkinker 时遇到了问题。你们能否提供有关如何使我的输出正常工作的提示?我发现get()即使使用在线教程也很难使用该方法。

各位大佬能教一下这个小白吗?谢谢!

我的原始代码:

# 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()

标签: pythontkinter

解决方案


您需要一个按钮来更新您的代码,因为最初这些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

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

干杯


推荐阅读