How to write commands to terminal using tkinter? - python

I wanted to do something like , if i type something in textbox that command would get executed completely
like this
ie the ~Desktop should be displayed to write next command.
but with my code im getting this also there is an error
as you can see ls command gets executed half in second case
my code is
#!/usr/bin/python
import Tkinter
import subprocess
import tkMessageBox
from Tkinter import *
root = Tk()
class HackBar:
def __init__(self,master):
frame=Frame(master,width = 600,height = 250)
#frame.pack()
def printconsole(event):
print("hello dere ")
def retrieve_input(event):
input = self.Text.get("1.0",'end-1c')
#print(input)
#subprocess.call(input,shell=TRUE)
subprocess.Popen(input)
root.quit()
#root = Tk()
#print p.communicate()
self.button1 = Button(root,text = "Execute")
self.button1.bind("<Button-1>",retrieve_input);
self.button1.grid(row = 0,sticky = E)
self.button2 = Button(root,text = " Quit ")
self.button2.bind("<Button-1>",printconsole);
self.button2.grid(row = 1,sticky = E)
self.Text = Text(root,height =4)
self.Text.grid(row = 0,column = 1,rowspan=2)
menu = Menu(root)
def AboutDialog():
tkMessageBox.showinfo('About','For any issues or suggestion contact rushic24#gmail.com ')
root.config(menu = menu)
submenu1 = Menu(menu)
menu.add_cascade(label="Help",menu=submenu1)
submenu1.add_command(label = "About",command = AboutDialog)
b = HackBar(root)
root.mainloop()
i think i need to use the root.quit() and would again need to start root ,
but it is giving the above error.
Any alternate method would also work.

Related

Getting Input From a Tkinter Class by Another Class

I am trying to connect my tkinter code with another program. That is, I am trying to call the GUI file from the the other program and receive input from the GUI program, but I am having issues.
Here is the GUI code called BayeGUI
from tkinter import *
import tkinter.simpledialog
class BayeGUI:
def __init__(self):
window = Tk()
window.title('Graphical User Interface Designed by Gideon')
self.input = 'I am fine Thank you'
frame1 = Frame(window)
frame1.pack()
self.v1 = StringVar()
scrollbar = Scrollbar(frame1)
scrollbar.pack(side = RIGHT, fill = Y)
self.text = Text(frame1, width = 100, height = 30,wrap = WORD, yscrollcommand = scrollbar.set)
scrollbar.config(command = self.text.yview)
self.text.pack()
frame2 = Frame(window)
frame2.pack()
testbtn = Button(frame2,text = 'Test Algorithm',command = self.testAlgorithm)
testbtn.grid(row = 1, column = 1)
return self.input
window.mainloop()
def testAlgorithm(self):
isYes = tkinter.messagebox.askyesno('askyesno', 'Do you want to Test the Algorithm?')
if isYes == True:
self.input = self.text.get("1.0",'end-1c') #This is the input I need
BayeGUI()
This is the main code where I am trying to get value fron Baye GUI.
from BayeGUI import BayeGUI
emails = BayeGUI()
print(emails)

How to save a data after closing a window?

I'm trying to make some GUI on Python3 with tkinter. So far I have Main Window and 'Test' button on it, which opens second window. Second window has entry, label, save and close buttons. When you type something in entry and press save button, label shows the text you typed in entry. But after closing this window and opening it again, label shows nothing. How do I make this label to show the text that were typed last time before closing? For example, I type 'Hi' in entry, press 'Save', then I press 'Close', then I open this window again and label shows 'Hi'
import tkinter as tk
def save_data(entry, t):
t.config(text = entry.get())
def close_action(current_window):
current_window.destroy()
def insertMainInfo():
new_window = tk.Tk()
new_window.geometry("307x131")
new_window.title("TestWindow")
test_entry = tk.Entry(new_window)
test_entry.place(relx = 0.283, rely = 0.1, height = 24, width = 127)
text = tk.Label(new_window)
text.place(relx = 0.283, rely = 0.25, height = 24, width = 127)
save_button = tk.Button(new_window, command = lambda: save_data(test_entry, text))
save_button.place(relx=0.283, rely=0.45, height=24, width=127)
save_button.configure(text = "Save")
close = tk.Button(new_window, command = lambda: close_action(new_window))
close.place(relx=0.283, rely=0.687, height=24, width=127)
close.configure(text = "Close")
new_window.mainloop()
if __name__ == '__main__':
top = tk.Tk()
top.geometry("307x131+557+330")
top.resizable(width=False, height=False)
top.title("MainWindow")
new_window_button = tk.Button(top, command = insertMainInfo)
new_window_button.place(relx=0.283, rely=0.687, height=24, width=127)
new_window_button.configure(text = "Test")
main_label = tk.Label(top)
main_label.place(relx=0.033, rely=0.153, height=41, width=284)
main_label.configure(text = "TestLabel")
top.mainloop()
I have to confess that your question heading is a bit ambiguity.
If you just want to update a label of last entry, here a simple way of modifying your code.
As advised, as a good practice we only have one Tk() in a program, other new windows or pop-up windows should use Toplevel() of tkinter class; So I use this in your insertMainInfo() function.
The point here is to define a variable, I called last_entry and initially is empty or ‘’. Use this as parameter in new_window button in main program (after if __name__ == '__main__': ) to this variable (I also add lambda function here).
Then we define it as global in save_data function, so as it can be known later by other functions or main program as the last entry before new_window is closed.
Here I modify your code as said above, and I have tested it, and it works as expected.
import tkinter as tk
def save_data(entry, t):
global last_entry
last_entry = entry.get()
t.config(text = last_entry)
def close_action(current_window):
current_window.destroy()
def insertMainInfo(last_entry):
new_window = tk.Toplevel()
new_window.geometry("307x131")
new_window.title("TestWindow")
test_entry = tk.Entry(new_window)
test_entry.place(relx = 0.283, rely = 0.1, height = 24, width = 127)
text = tk.Label(new_window, text=last_entry)
text.place(relx = 0.283, rely = 0.25, height = 24, width = 127)
save_button = tk.Button(new_window, command = lambda: save_data(test_entry, text))
save_button.place(relx=0.283, rely=0.45, height=24, width=127)
save_button.configure(text = "Save")
close = tk.Button(new_window, command = lambda: close_action(new_window))
close.place(relx=0.283, rely=0.687, height=24, width=127)
close.configure(text = "Close")
new_window.mainloop()
# --- A Simple Data Structure ---
last_entry = ''
if __name__ == '__main__':
top = tk.Tk()
top.geometry("307x131+557+330")
top.resizable(width=False, height=False)
top.title("MainWindow")
new_window_button = tk.Button(top, command = lambda: insertMainInfo(last_entry))
new_window_button.place(relx=0.283, rely=0.687, height=24, width=127)
new_window_button.configure(text = "Test")
main_label = tk.Label(top)
main_label.place(relx=0.033, rely=0.153, height=41, width=284)
main_label.configure(text = "TestLabel")
top.mainloop()

StringVar DoubleVar and others

I am very new on Python and I have a problem.
I try to read my temperature sensor and set the Value in to my Tkinter GUI.
I don't know how to update my label LT with the new value if I update it with my Button B1.
I have tried everything from StringVar to get() and this stuff.
I hope you can help me to find my failure.
Here is my code:
from tkinter import *
import os
Main = Tk()
Main.title("Hauptmenü")
Main.geometry("500x400")
class Fenster():
def Credit():
messagebox.showinfo(title="Credits",message="created by T.N v0.1")
return
def Beenden():
pExit = messagebox.askyesno(title="Beenden",message="Möchten Sie\n wirklich beenden?")
if pExit > 0:
Main.destroy()
return
def auslesen(event):
file = open("/sys/bus/w1/devices/28-041635ad4cff/w1_slave")
inhalt = file.read()
trennwoerter = inhalt.split(" ")
Wert = (trennwoerter[20])
Temp = (Wert[2:4])
file.close()
labelauslesen = Label(Main,text="Aktuelle Temperatur :")
labelauslesen.pack()
LT = Label(Main,text=Inhalt)
LT.pack()
B1 = Button(Main,text="Temperatur auslesen")
B1.pack()
B1.bind("<Button-1>",auslesen)
menubar=Menu(Main)
filemenu = Menu(menubar)
filemenu.add_command(label="Sensoren auslesen")
filemenu.add_command(label="Diagram anzeigen")
filemenu.add_command(label="Credits",command = Credit)
filemenu.add_command(label="Beenden",command = Beenden)
menubar.add_cascade(label="Datei",menu=filemenu)
Main.config(menu=menubar)
mainloop()
A minimal example that you can adapt to your code.
import tkinter as tk
root=tk.Tk()
temp = 10.0
def update_temp():
global temp
temp += 1.3
tlabel['text'] = '%s degrees C' % round(temp, 1)
tlabel = tk.Label(root, text='unknown')
tbutton = tk.Button(root, text='new temp', command=update_temp)
tlabel.pack()
tbutton.pack()
root.mainloop()

How would I create a reset button for my program relating with the following code?

I am trying to add a reset button but I can't seem to get it to work. I created a main in order to refer back to it when the button is pressed but no luck. Any ideas?
import sys
from tkinter import *
import math
def main():
def closeWin():
myGui.destroy() #Close Window Function
def kiloFunc():
myText = kiloMent.get() #Kilometers to Miles Fuction
convert = 0.62
miles = myText * convert
finalKilo = Label(text = miles,fg='red',justify='center').place(x=200,y=80)
def mileFunc():
myText2 = mileMent.get() #Miles to Kilometers Function
convertTwo = myText2 // 0.62
finalMile = Label(text = convertTwo, fg = 'red',justify='center').place(x=200,y=170)
myGui = Tk()
kiloMent = IntVar()
mileMent = IntVar()
myGui.title("Distance Converter")
myGui.geometry("450x200+500+200")
myLabel = Label(text="Welcome! Please enter your value then choose your option:",fg="blue",justify='center')
myLabel.pack()
kiloEntry = Entry(myGui, textvariable = kiloMent,justify='center').pack()
kilo2milesButton = Button(text = "Kilometers to Miles!", command = kiloFunc).pack()
mileEntry = Entry(myGui, textvariable = mileMent,justify='center').place(x=130,y=105)
miles2kiloButton = Button(text = "Miles to Kilometers!", command = mileFunc).place(x=150,y=135)
reset = Button(text = "Reset Values!", command = main).place(x=10,y=165)
quit = Button(text="Quit", command = closeWin).place(x=385,y=165)
myGui.mainloop()
main()
By calling main() again, you are simply creating another instance of the GUI. What you should do instead is (if I understand correctly), reset the values of the currently existing GUI. You can use the set() method of the GUI objects.
Does
def reset_values():
kiloMent.set(0)
mileMent.set(0)
reset = Button(text="Reset Values!", command=reset_values).place(x=10, y=165)
do the trick?
Looking at your code more thoroughly, however, there are some other problems there, as well. To start with, I would suggest not creating a Label everytime the user tries to convert a value.
This code should work:
from tkinter import *
def main():
def closeWin():
myGui.destroy() # Close Window Function
def kiloFunc():
finalKilo.set(kiloMent.get() * 0.62) # Kilometers to Miles Fuction
def mileFunc():
finalMile.set(mileMent.get() // 0.62) # Miles to Kilometers Function
def clearFunc():
kiloMent.set("0")
mileMent.set("0")
finalKilo.set("")
finalMile.set("")
myGui = Tk()
kiloMent = IntVar()
mileMent = IntVar()
finalKilo = StringVar()
finalMile = StringVar()
myGui.title("Distance Converter")
myGui.geometry("450x200+500+200")
myLabel = Label(text="Welcome! Please enter your value then choose your option:", fg="blue", justify='center')
myLabel.pack()
kiloEntry = Entry(myGui, textvariable=kiloMent, justify='center')
kiloEntry.pack()
kilo2milesButton = Button(text="Kilometers to Miles!", command=kiloFunc)
kilo2milesButton.pack()
mileEntry = Entry(myGui, textvariable=mileMent, justify='center')
mileEntry.place(x=130, y=105)
miles2kiloButton = Button(text="Miles to Kilometers!", command=mileFunc)
miles2kiloButton.place(x=150, y=135)
kiloLabel = Label(textvariable=finalKilo, fg='red', justify='center')
kiloLabel.place(x=200, y=80)
mileLabel = Label(textvariable=finalMile, fg='red', justify='center')
mileLabel.place(x=200, y=170)
reset = Button(text="Reset Values!", command=clearFunc)
reset.place(x=10, y=165)
quit = Button(text="Quit", command=closeWin)
quit.place(x=385, y=165)
myGui.mainloop()
main()
A few notes about your original code besides the ones that Chuck mentioned:
The math and sys imports were unused.
You were setting variables equal to widget.pack() and widget.place(), which are functions that return None.

How can I use the output from tkFileDialog.askdirectory to fill a tkinter Entry box

I have a tkinter Entry box in which the user can insert a path to the directory. Alternatively the user can click a button to select the directory. How can I set the output from the button to fill the Entry box? I have tried the following but dirname is not a global variable and so is not recognised by UserFileInput. Also how can I bind the button next to the entry field.
from Tkinter import *
import tkFileDialog
def askdirectory():
dirname = tkFileDialog.askdirectory()
return dirname
def UserFileInput(status,name):
optionFrame = Frame(root)
optionLabel = Label(optionFrame)
optionLabel["text"] = name
optionLabel.pack(side=LEFT)
text = str(dirname) if dirname else status
var = StringVar(root)
var.set(text)
w = Entry(optionFrame, textvariable= var)
w.pack(side = LEFT)
optionFrame.pack()
return w
if __name__ == '__main__':
root = Tk()
dirBut = Button(root, text='askdirectory', command = askdirectory)
dirBut.pack(side = RIGHT)
directory = UserFileInput("", "Directory")
root.mainloop()
Your UserFileInput should return var, not w. Then you can use var.set(dirname) in your askdirectory function which doesn't have to return anything.
I'm not sure however what you try to achieve with text = str(dirname) if dirname else status. Why not just use text = status since dirname can't yet be defined there?
Edit:
This should work the way you want it to. The 'print entry text' button shows that you can retreive whatever is in the entry box, either written by the user or put there by the code.
from Tkinter import *
import tkFileDialog
def askdirectory():
dirname = tkFileDialog.askdirectory()
if dirname:
var.set(dirname)
def UserFileInput(status,name):
optionFrame = Frame(root)
optionLabel = Label(optionFrame)
optionLabel["text"] = name
optionLabel.pack(side=LEFT)
text = status
var = StringVar(root)
var.set(text)
w = Entry(optionFrame, textvariable= var)
w.pack(side = LEFT)
optionFrame.pack()
return w, var
def Print_entry():
print var.get()
if __name__ == '__main__':
root = Tk()
dirBut = Button(root, text='askdirectory', command = askdirectory)
dirBut.pack(side = RIGHT)
getBut = Button(root, text='print entry text', command = Print_entry)
getBut.pack(side = BOTTOM)
w, var = UserFileInput("", "Directory")
root.mainloop()

Categories