微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用Python Tkinter模块进行编码时遇到问题

如何解决使用Python Tkinter模块进行编码时遇到问题

最近,我在使用Python Tkinter模块进行编码时遇到问题。

该项目是一个URL缩短器。

(I was not allowed to post actual photo out here yet) Click here to see the picture that illustrated how my project looks.

这是我写的代码

import tkinter as tk
import random 
import string

def shorten_url():
    url = url_input_space_entry.get()
    result_url_random_part = ''.join(random.choice(string.hexdigits) for digit in range(6))
    result_url = f"www.urlshort.com/{result_url_random_part}"
    show_result.configure(text=result_url)

window = tk.Tk()
window.title("URL Shortener")
window.geometry("700x600")

app_title = tk.Label(window,text="URL Shortener")
app_title.pack()

url_input_space = tk.Frame(window)
url_input_space.pack()
url_input_label = tk.Label(url_input_space,text="Please enter your URL: ")
url_input_label.pack(side=tk.LEFT)
url_input_space_entry = tk.Entry(url_input_space,width=45)
url_input_space_entry.pack()

result_frame = tk.Frame(window)
result_frame.pack()
result_label = tk.Label(result_frame,text="Result: ")
result_label.pack(side=tk.LEFT)
show_result = tk.Entry(result_frame,width=34)
show_result.pack()

shorten_url_button = tk.Button(window,text="Shorten it",command=shorten_url)
shorten_url_button.pack()

window.mainloop()

所以,我希望:

首先,我输入需要缩短的URL:

请输入您的URL:xxxx.com(示例URL)

然后,在我按下“ Shorten it”按钮之后,这就是我希望进入结果框架的结果:

结果:www.urlshort.com/XXXXXX随机的6位数字和字母,例如9eDS34,A1e2wS等)

但是现在,按下按钮后,RESULT框什么也没有显示。 (之所以对这个问题一无所知,是因为在我运行程序之后,没有出现错误消息。)

有人可以告诉我我写错了什么,如何解决?非常感谢!

解决方法

您不能将配置方法与Entry小部件一起使用。 相反,您应该清除Entry,然后像这样插入您的字符串:

show_result.delete(0,tk.END)
show_result.insert(0,result_url)

您的主要代码应为

def shorten_url():
    url = url_input_space_entry.get()
    result_url_random_part = ''.join(random.choice(string.hexdigits) for digit in range(6))
    result_url = f"www.urlshort.com/{result_url_random_part}"
    show_result.delete(0,tk.END)
    show_result.insert(0,result_url)

window = tk.Tk()
window.title("URL Shortener")
window.geometry("700x600")

app_title = tk.Label(window,text="URL Shortener")
app_title.pack()

url_input_space = tk.Frame(window)
url_input_space.pack()
url_input_label = tk.Label(url_input_space,text="Please enter your URL: ")
url_input_label.pack(side=tk.LEFT)
url_input_space_entry = tk.Entry(url_input_space,width=45)
url_input_space_entry.pack()

result_frame = tk.Frame(window)
result_frame.pack()
result_label = tk.Label(result_frame,text="Result: ")
result_label.pack(side=tk.LEFT)
show_result = tk.Entry(result_frame,width=34)
show_result.pack()

shorten_url_button = tk.Button(window,text="Shorten it",command=shorten_url)
shorten_url_button.pack()

window.mainloop()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。