首页 > 解决方案 > How to return a value from a function to another function with Tkinter?

问题描述

This is my problem. I can not return the value of the randomtext() function to the main function.

I want the text to be selected to be copied and then pasted somewhere. Using a Label works, but when I use an Entry it does not work. What am I doing wrong?

def psw_generator():
    global gen
    genpassw = Tk()
    genpassw.title("password generator")

    entrypassw = Entry(parent, textvariable = gen, state = DISABLED)
    entrypassw.pack()


def randomtext():

    x = 0
    psw = ""
    lenght = 16
    full_char_table = "abcdef.."
    type = full_char_table

    gen = StringVar(value = psw)

    for x in range(int(lenght)):
        psw += type[int(random.randrange(len(type)))]
        x += 1

    return gen

标签: pythonfunctiontkinter

解决方案


这段代码有很多问题,所以我已经解决了,你完成的代码在这里:

import random
from tkinter import *

global gen
genpassw = Tk()
gen = StringVar()
genpassw.title("password generator")

entrypassw = Entry(genpassw, textvariable = gen, state = DISABLED)
entrypassw.pack()
def randomtext():
    global gen
    x = 0
    psw = ""
    length = 16
    full_char_table = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"


    for x in range(int(length)):
        psw += full_char_table[random.randint(0,len(full_char_table)-1)]

    gen.set(psw)

randomtext()
genpassw.mainloop()

所以看看你的问题

entrypassw = Entry(parent, textvariable = gen, state = DISABLED)

您需要使用 genpassw 的条目小部件中的“父”是什么,因为那是您的父小部件。

type = full_char_table

你曾经使用'type'作为变量,'type'是python的内置函数,所以你不能使用它。

x += 1

无需在 for 循环中使用增量>> x += 1

entrypassw = Entry(parent, textvariable = gen, state = DISABLED)
entrypassw.pack()

return gen

您正在返回 gen.Before 您将它们描述为小部件的文本变量,现在您正在返回它。它已被弃用。

您必须使用 mainloop 使您的 GUI 运行。

genpassw.mainloop()

推荐阅读