Is there a way to return something when a button is pressed?
Here is my sample program. a simple file reader. Is the global variable to hold text contents the way to go since I can't return the contents?
from Tkinter import *
import tkFileDialog
textcontents = ''
def onopen():
filename = tkFileDialog.askopenfilename()
read(filename)
def onclose():
root.destroy()
def read(file):
global textcontents
f = open(file, 'r')
textcontents = f.readlines()
text.insert(END, textcontents)
root = Tk()
root.title('Text Reader')
frame = Frame(root)
frame.pack()
text = Text(frame, width=40, height=20)
text.pack()
text.insert(END, textcontents)
menu = Menu(root)
root.config(menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="Open...", command=onopen)
filemenu.add_command(label="Exit", command=onclose)
mainloop()
Tk(inter) is event-based, which means, that you do not return values, but bind callbacks (functions) to actions.
more info here: http://effbot.org/tkinterbook/button.htm
If you meant signal back to the user, here's some sample code:
import Tkinter
import tkMessageBox
top = Tkinter.Tk()
def helloCallBack():
tkMessageBox.showinfo( "Hello Python", "Hello World")
B = Tkinter.Button(top, text ="Hello", command = helloCallBack)
B.pack()
top.mainloop()
and the source: Python - Tkinter Button tutorial
Related
It is pretty obvious that I'm pretty new to python and I am trying to make a simple GUI with tkinter that would have two buttons. One "Browse" to open file, and for example "Run" to make some operations with this file.
This is the function that I used for File browser, but how to pass this file location to other functions.
def open():
result = filedialog.askopenfile(initialdir="/C")
print(result)
This is the code so far without any special editing.
from tkinter import *
from tkinter import filedialog
import os
root = Tk()
#root.filename = filedialog.askopenfilename(initialdir="/C")
def open():
result = filedialog.askopenfile(initialdir="/C")
print(result)
c=result
return c
theLabel = Label(root, text="The Editor")
theLabel.grid(row=0)
button1 = Button(root, text="Browse", command=open)
button2 = Button(root, text="Run")
button3 = Button(root, text="Quit", command=root.quit)
button1.grid(row=1)
button2.grid(row=2)
button3.grid(row=3)
root.mainloop()
This is where classes make things a little easier:
from tkinter import *
from tkinter import filedialog
import os
class GUI():
def __init__(self):
self.root = Tk()
self.filename = ""
#root.filename = filedialog.askopenfilename(initialdir="/C")
theLabel = Label(self.root, text="The Editor")
theLabel.grid(row=0)
button1 = Button(self.root, text="Browse", command=self.open)
button2 = Button(self.root, text="Run", command=self.other_func)
button3 = Button(self.root, text="Quit", command=self.root.quit)
button1.grid(row=1)
button2.grid(row=2)
button3.grid(row=3)
self.root.mainloop()
def open(self):
result = filedialog.askopenfilename(initialdir="C:/")
print("Function open read:")
print(result)
self.filename = result
#print("Set class attribute, calling other function")
#self.other_func()
def other_func(self):
with open(self.filename) as f: # 'with' is preferred for it's error handling
for c in f:
print(c)
GUI()
Well you can return the variable:
def open():
result = os.path.dirname(os.path.abspath(__file__))
return result
file_path = open()
Later you can use file_path and pass it to a new function.
You could also immediately call that function from inside the open function while passing result:
def open():
result = os.path.dirname(os.path.abspath(__file__))
your_function(result)
I changed the way you get the file path. I would also advise against naming a function open(), since it already is a function in itself:
https://docs.python.org/3/library/functions.html#open
I need help, I am doing a budget calculator and using tkinter for the first time and wondered why it is not working...
When I run it, it will just end straight away and when I put the root = Tk() at the end it comes up with an error.
I really need help, my code is below...
from time import sleep
from tkinter import *
from tkinter import messagebox, ttk, Tk
root = Tk()
class GUI():
def taskbar(self):
menu = Menu()
file = Menu(menu)
file.add_command(label="Exit", command=self.exit_GUI)
file.add_command(label = "Information", command=self.info_popup)
def Main_Menu(self):
topFrame = Frame(root)
topFrame.pack()
bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM)
Income_button = Button(topFrame, text="Enter your incomes", command=self.Income)
Expense_button = Button(topFrame, text="Enter your expenses", command=self.Expense)
Total_button = Button(bottomFrame, text="View Results", command=self.Total)
Income_button.pack()
Expense_button.pack()
Total_button.pack()
def Income(self):
pass
def Expense(self):
pass
def Total(self):
pass
def exit_GUI(self):
exit()
def info_popup():
pass
g = GUI()
g.Main_Menu()
g.taskbar()
g.Income()
g.Expense()
g.Total()
g.exit_GUI()
g.info_popup()
root.mainloop()
You are exiting before you ever get to the mainloop with:
g.exit_GUI()
That method is calling the standard exit() and stopping the entire script. Remove or comment out the above call. You will also need to add self as an argument to info_popup to get your script to run:
def info_popup(self):
pass
Does anyone know why it will not show the taskbar in my code. I am trying to get the top to say Exit and information in the file drop down menu. I am kind of new to tkinter and i just need a bit of help please. Also if you have any suggestions on how to improve it, i would really appreciate it!
My code is below:
from time import sleep
from tkinter import *
from tkinter import messagebox, ttk, Tk
root = Tk()
class GUI():
def taskbar(self):
menu = Menu(root)
file = Menu(menu)
file.add_command(label="Exit", command=self.exit_GUI)
file.add_command(label = "Information", command=self.info_popup)
def Main_Menu(self):
topFrame = Frame(root)
topFrame.pack()
bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM)
Income_button = Button(topFrame, text="Enter your incomes", command=self.Income)
Expense_button = Button(topFrame, text="Enter your expenses", command=self.Expense)
Total_button = Button(bottomFrame, text="View Results", command=self.Total)
Income_button.pack()
Expense_button.pack()
Total_button.pack()
def Income(self):
pass
def Expense(self):
pass
def Total(self):
pass
def exit_GUI(self):
exit()
def info_popup(self):
pass
g = GUI()
g.taskbar()
g.Main_Menu()
g.Income()
g.Expense()
g.Total()
g.info_popup()
root.mainloop()
You need to change the taskbar function to:
def taskbar(self):
menu = Menu(root)
file = Menu(menu)
file.add_command(label="Exit", command=self.exit_GUI)
file.add_command(label = "Information", command=self.info_popup)
root.config(menu=file)
This will tell the window to use the menubar.
I have created an coding gui,which doesnot show 'File' and 'save' in the Gui
Please help me to fix my problem.
I have created a Function for File and Save ,still not working!
please help me to rectify my code!
from tkinter import *
import tkinter.messagebox
import tkinter
import tkinter as tki
import tkinter.filedialog as th1
import re
class App(object):
def __init__(self,root):
self.root = root
# create a Frame for the Text and Scrollbar
txt_frm = tki.Frame(self.root, width=600, height=400)
txt_frm.pack(fill="both", expand=True)
# ensure a consistent GUI size
txt_frm.grid_propagate(False)
# create first Text label, widget and scrollbar
self.lbl1 = tki.Label(txt_frm, text="Type")
self.lbl1.grid(row=0,column=0,padx=2,pady=2)
self.txt1 = tki.Text(txt_frm, borderwidth=3, relief="sunken", height=4,width=55)
self.txt1.config(font=("consolas", 12), undo=True, wrap='word')
self.txt1.grid(row=0, column=1, sticky="nsew", padx=2, pady=2)
scrollb1 = tki.Scrollbar(txt_frm, command=self.txt1.yview)
scrollb1.grid(row=0, column=2, sticky='nsew')
self.txt1['yscrollcommand'] = scrollb1.set
button = tki.Button(txt_frm,text="Clickone", command = self.retrieve_input)
button.grid(column=2,row=0)
button1 = tki.Button(txt_frm,text="Cli", command = self.clearBox)
button1.grid(column=2,row=0)
def retrieve_input(self):
input1 = self.txt1.get("0.0",'end-1c')
with open('text.txt','a+') as f:
f.write(input1+'\n')
f.close()
def clearBox(self):
self.txt1.delete('1.0', 'end')#<-0.0/1.0
def file_save():
f = th1.asksaveasfile(mode='w', defaultextension=".txt")
if f is None: # asksaveasfile return `None` if dialog closed with "cancel".
return
text2save = str(text.get(1.0, END))
a= (f)
f.write(text2save)
f.close()
root = tki.Tk()
menubar=Menu(root)
filemenu=Menu(menubar,tearoff=0)
filemenu.add_command(label="Save", command=file_save)
app = App(root)
root.mainloop()
Please help!Answers will be appreciated!
You aren't adding the menubar to the window. Add this after you create the menubar.
root.configure(menu=menubar)
You then also have to add the file menu to the menubar:
menubar.add_cascade(label="File", menu=filemenu)
So, what I am trying to do is open a file when pressing a button and displaying the contents in a listbox. This is what I have so far, but I am not getting the listbox to display, let alone get the info to be in the listbox:
#!/usr/bin/perl -w
import time
from Tkinter import *
import tkFileDialog
def listbox(listbox):
def open_file():
file = tkFileDialog.askopenfilename()
openFile = open(file)
for line in openFile:
listbox.insert(END, line)
open_file()
class App:
def __init__(self, parent):
frame = Frame(parent.title("Buttons"))
frame.pack()
root.pack_propagate(0)
self.exit = Button(frame, text="QUIT", fg="red", command=frame.quit)
self.exit.pack(side=LEFT)
self.open = Button(frame, text="Open...", command=self.call_listbox)
self.open.pack(side=LEFT)
frame.listbox = Frame()
scrollme = Scrollbar(frame.listbox)
self.listbox = Listbox(frame.listbox, yscrollcommand = scrollme.set)
scrollme.config(command = self.listbox.yview)
scrollme.pack(side = RIGHT, fill = Y)
self.listbox.pack()
self.listbox.insert(END, "Code:")
def call_listbox(self):
listbox(self.listbox)
root = Tk()
app = App(root)
root.mainloop()
any suggestions? thanks
You are forgetting to pack the frame that contains the listbox.
FWIW, your overloading of the name "listbox" makes your code very confusing - you have def listbox(listbox), self.listbox and frame.listbox. And you also have call_listbox and the Listbox class to add to the confusion.