I know this question is discussed in forums ad I have read about it a lot but I still dont have solution I need.
Following code is very simplified version of my real code.
My first script is following(kyssa1.py):
import os
import sys
def type():
global dictionary
dictionary="C:\Python27\Myprojects\physics.txt"
os.system("C:\Python27\Myprojects\kyssa2.py")
from Tkinter import *
t = Tk()
b = Button(t, text="Start", command = lambda:type())
b.pack(expand=Y)
t.mainloop()
And my second script (kyssa2.py) is following:
# -*- coding: utf-8 -*-
from kyssa1 import dictionary
def open():
global dictionary
global lines
global datafile
datafile = file(dictionary)
lines = [line.decode('utf-8').strip() for line in datafile.readlines()]
for i in lines:
text.insert(END, i)
open()
from Tkinter import *
root = Tk()
text = Text(root,font=("Purisa",12))
text.pack()
root.mainloop()
What I want to do is to open file physics.txt in kyssa2.py and execute command in function open() with this text, but it doesn't wor the way I want to. What happens when I click "Start" button is another window just like defined in "kyssa1.py" appears. How could I just pass variable dictionary from one script to another?
In kyssa1.py declare dictionary in module scope, i.e.outside of the type() function.
You don't need to use global in kyssa2.py, you can refer directly to dictionary.
Also, to open the file, use open() rather than file():
datafile = open(dictionary)
Related
I have two python files. In this example I have made it really simple, File_A and File_B. In File_A I want to define a variable, and in File_B I want to use this variable to do something.
The code is a bit more complex, but this is the idea:
FileA:
import tkinter as tk
window = tk.Tk()
entry = tk.Entry(window)
entry.pack()
button = tk.Button(window, text="Click me!", command=lambda: on_button_click(entry.get()))
button.pack()
def on_button_click(ip):
pass
#changing variable in File_B to 'ip'
#run File_B
window.mainloop()
File_B:
print(value) #value entered in File_A
I have tried things in File_B like:
From File_A import value
But this didn't seem to work for me, or it made the GUI open once more.
Does anyone have a suggestion?
You can wrap the file's code with a function instead, and pass relevant variables using the function parameters.
TestB:
def main(ip):
print(ip)
<rest of code for file TestB>
TestA:
import TestB
def on_button_click(ip):
TestB.main(ip)
Maybe add more details to your question (what are you trying to do?), there might be a more efficient way to solve this problem.
I have created two python programs. One in which I am doing all the manipulations like sorting the data in Excel file using xlrd and xlwt. Another is I created a GUI using Tkinter and importing the original Excel file on which I need to do the manipulations
My question is how to add this program for manipulation in Tkinter program so that on click I will get required file with all the manipulations done. Both the programs are working individually
Use the import keyword:
Put both files in the same directory, name them like variables (the name does not start from a number, contain dashes etc. Example: gui.py and operations.py)
Put everything from the operations file (except imports) in a function. Example:
import random
def main():
for x in range(10):
print(random.randint(1,10))
Use the import keyword:
from tkinter import Tk, Button
import operations
tk = Tk()
Button(tk, command=operations.main).pack()
tk.mainloop()
where operations (twice) is the name of your file with a function, minus the .py part, and main - the name of a functon.
There's a different way, a bad one, that's os-specific but does not require the main function. Depending on the OS you could try:
import os
os.system('python3 operations.py')# variation 1
os.system('python operations.py')# variation 2
os.system('py -3 operations.py')# variation 3
Hope that's helpful!
I just moved from Matlab to Python. So I am looking hopefully to re-build my GUI in Matlab Guide with Page Python (only hopeful for better performance for big data)
I designed several Push Buttons and inside the code I try to write the below code just beneath Button1.configure.
I can not take out seop value from this clicked () function although I even define it as global variable. I need seop for whole the program.
self.Button1.configure(text='''Data''')
def clicked():
global seop
from tkinter import filedialog, messagebox
fname = filedialog.askopenfilename (initialdir="C:\Sgty")
import numpy as np
seop = np.loadtxt (fname)
messagebox.showinfo ('Data Import', 'Int')
s1 = self.Button1.configure (command=clicked, text="Import Data")
I am working on a program that allows me to directly edit a word document through a tkinter application. I am trying to link the tkinter input from my gui file to my main file so that I can execute my docx functions. When I try to execute my code this way, it tells me that entry in entry.get() is not defined. When I try to import this from main, I receive a circular import error.
main.py
from docx import Document
from docx.shared import Inches
import os
os.chdir("\\Users\\insanepainz\Desktop")
doc = Document('TemplateTest.docx')
paragraphs = doc.paragraphs
def WebsiteChange():
website = entry.get()
print(website)
master.quit()
for paragraph in doc.paragraphs:
if '^website' in paragraph.text:
paragraph.text = gui.entry
print(paragraph.text)
doc.save(doc)
pass
gui.py
import main
from tkinter import *
master = Tk()
#------------Web Entry Window
Label(master, text="Website Name: ").grid(row=0, sticky=W)
entry = Entry(master)
entry.grid(row=0, column=1)
# Connect the entry with the return button
submit = Button(master, text="Submit", command=main.WebsiteChange)
submit.grid(row=1)
# Centers the program window
master.eval('tk::PlaceWindow %s center' % master.winfo_pathname(master.winfo_id()))
mainloop()
I have been struggling to understand this concept for awhile. Circular errors are giving me a headache. Any help would be greatly appreciated.
The import mechanism is designed to allow circular imports. But one must remember the following:
The name of the main module created from the startup script is __main__, rather than as its filename minus .py. Any other file importing the startup script must import __main__, not import filename. (Otherwise, a second module based on the startup script will be created with its normal name.)
Execution of the code in a module is paused at each import. The order of initial imports is important as the last module in the chain is the first to be run to completion. Each object within modules must be available when the reference is executed. References within function definitions are not executed during the import process.
Applying the above to your pair, I assume that gui.py is the startup script. Python will immediate create an empty module object as the value of sys.modules['__main__']. Somain.pyshould importgui.pywithimport main as gui(the name change is just for convenience). Within the function definition, you should be able to usegui.entrywithout problem since there will be no attempt to lookupgui.entryuntil the function is called. I suggest addingentry = gui.entryas the first line of the function and usingentry` in the two places needed.
The following pair of files run as desired when tem2.py is run.
# tem2.py
import tem3
a = 3
print(tem3.f())
# tem3.py
import __main__ as tem2
def f():
return tem2.a
Move the definition of entry into a third file and import it in both files.
You can pass the entry to WebsiteChange:
def WebsiteChange(entry):
website = entry.get()
submit = Button(master, text="Submit",
command=lambda e=entry: main.WebsiteChange(e))
I am a newbie in Python and am creating a Tkinter GUI that basically allows users to find desired keywords in .docx files. I have two buttons that both load a pickle file and only one may also add content to the file and save. After using the file under one function(button) and trying to load it up again under the other function(button) the file does not load. It will only load up again after I fully exit the program and run it again. I am not using classes for this program, but I feel that I may have to. I am just not able to bounce between these functions and successfully pass the file. Any advice would be greatly appreciated. Here is the code that may be most useful for this question:
from Tkinter import *
import tkMessageBox
import sys,os,glob,pickle
root = Tk()
root.geometry('400x300')
root.title('Potential Candidate Engine')
Pickle_File = ('Diction.pickle')
if os.path.exists(Pickle_File):
with open(Pickle_File,'r') as rPF:
Dictionary = pickle.load(rPF)
def Clear_Window():
RETURN = sys.executable
os.execl(RETURN, RETURN, * sys.argv)
def SR():
global Dictionary
### Scan the document here ###
def CNP():
global Dictionary
### User adds content here, file saves ###
That 'Clear_Window()' function is just a workaround to return to the main window after the user is done with one function and would like to use the other. It is executed when the RETURN button is pushed