简体   繁体   English

无法弄清楚如何在另一个函数中使用一个函数中的变量 - Python

[英]Can't figure out how to use a variable from one function in another - Python

I am working on a small project to help me consolidate my learning of python.我正在做一个小项目来帮助我巩固我对 Python 的学习。 After endless trial with global variables, and returns;经过对全局变量的无休止的试验,并返回; and searching I have decided to post here.和搜索我决定在这里发帖。 Basically when the program is running, the user can select a .txt file from their computer and then the directory is recorded through the findFile() function specifically the my_label variable.基本上当程序运行时,用户可以从他们的计算机中选择一个 .txt 文件,然后通过 findFile() 函数特别是 my_label 变量记录目录。 I want to use the string stored in my_label to place it in the editFile function specifically the line: my_file = open("File location goes here","a+") in which it would look like my_file = open(my_label,"a+").我想使用存储在 my_label 中的字符串将它放在 editFile 函数中,特别是以下行: my_file = open("File location go here","a+") 其中它看起来像 my_file = open(my_label,"a+" )。 If anyone could provide help I would greatly appreciate it.如果有人可以提供帮助,我将不胜感激。

root = tk.Tk()

canvas1 = tk.Canvas(root, width = 400, height = 300)
canvas1.pack()

entry1 = tk.Entry (root) 
canvas1.create_window(200, 140, window=entry1)

def editFile ():

    x1 = entry1.get()

    label1 = tk.Label(root, text=x1 )
    canvas1.create_window(200, 230, window=label1)

    my_file = open("File location goes here","a+")

    my_file.read()

    my_file.write("\n" + x1)

    my_file.close()

def findFile ():
    root.filename = filedialog.askopenfilename(initialdir="C:\\Users\\mypc", 
title="Select A File", filetypes=(("txt files", "*.txt"),("All Files", "*.*"))) 
    my_label = Label(root, text=root.filename).pack() 
    canvas1.create_window(200, 290, window=my_label)

button1 = tk.Button(text='Enter Text', command=editFile)
canvas1.create_window(200, 180, window=button1)

button2 = tk.Button(text='Exit', command=root.destroy)
canvas1.create_window(200, 250, window=button2)

button3 = tk.Button(text='Find File', command=findFile)
canvas1.create_window(200, 270, window=button3)

root.mainloop()

In findFile() you should use global filename to put value in global variable filename instead of creating local one.findFile()您应该使用global filename findFile()值放入全局变量filename而不是创建本地变量。

In editFile() you don't have to use global because you only read value from variable.editFile()您不必使用global因为您只从变量中读取值。

But it is good to set default value at start filename = '' so you can check if filename was selected, and it will not raise error "variable doesn't exist" .但是最好在开始时设置默认值filename = ''这样您就可以检查是否选择了文件名,并且不会引发错误"variable doesn't exist"


BTW: at start I created labels without text and later I change text in existing labels instead of creating label again and again when different files will be selected.顺便说一句:一开始我创建了没有文本的标签,后来我更改了现有标签中的文本,而不是在选择不同文件时一次又一次地创建标签。


import tkinter as tk
from tkinter import filedialog

def editFile():
    #global filename # doesn't need to get value from global variable

    print(filename)

    text = entry1.get()

    # update text in existing `Label`
    label_text['text'] = text

    if filename: # dont't write if filename is not selected
        my_file = open(filename, "a")
        my_file.write("\n" + text)
        my_file.close()
    else:
        print('no filename')

def findFile():
    global filename # inform function to put value in global variable instead of creating local one

    filename = filedialog.askopenfilename(
        initialdir="C:\\Users\\mypc", 
        title="Select A File",
        filetypes=(("txt files", "*.txt"), ("All Files", "*.*"))
    )

    # update text in existing `Label`
    label_filename['text'] = filename

# --- main ---

filename = '' # (global variable) default value at start

root = tk.Tk()

canvas1 = tk.Canvas(root, width = 400, height = 300)
canvas1.pack()

entry1 = tk.Entry (root) 
canvas1.create_window(200, 140, window=entry1)

button1 = tk.Button(text='Enter Text', command=editFile)
canvas1.create_window(200, 180, window=button1)

button2 = tk.Button(text='Exit', command=root.destroy)
canvas1.create_window(200, 250, window=button2)

button3 = tk.Button(text='Find File', command=findFile)
canvas1.create_window(200, 270, window=button3)

# create only once and without text
label_filename = tk.Label(root)
canvas1.create_window(200, 290, window=label_filename)

# create only once and without text
label_text = tk.Label(root)
canvas1.create_window(200, 230, window=label_text)

root.mainloop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM