In Tkinter how do def work? - button

I made a Tkinter book on a grid, the navergation buttons scroll down the left row and the photos are displayed on the right column spaning many rows so buttons display as they should. When making this Tkinter book.
I made a button on a grid
left1 = Button(win, text=" Captian Scarlet ")# win, is root master
left1.configure(command=but1)# but1 is my first def
left1.grid(row=1, column=0)# all the buttons are on the left list
This displays and works like a button without a def
Then I made a def
def but1():
img = Image.open("captain_scarlett.gif")# loads the gif file
intro = ImageTk.PhotoImage(img)# loads image drivers I belevie
right1 = Label(win, image=intro)# I think Lable is used the same as html <span>
right1.grid(row=0, column=1, rowspan=13)# image formatting to display correctly with buttons
Because I had a lack of education at the time, I could only get the image to displaplay outside a def. So in frustration I posted
"this code works purfect when not put into a def".
When I settled down I needed knowledge that I couldn't find online so I asked the question:
So How do I get this code to work inside a def ?

What makes you think it doesn't work? There's nothing special about Tkinter in this regard; anything that works outside a def definitely works inside a def. The only caveats are the same for all python code. For example, any variables you create inside the def are local unless declared otherwise, and objects (but not widgets) may get garbage collected after the def executes.
Probably what is happening is that you're creating the image and storing a reference to it in a local variable. When the def stops executing the image object is garbage collected. You'll need to keep a reference to the image that can persist. One simple solution might be to do right1.image=intro.

This code works purfecty. Now my production can go full steam ahead
Here is the finished code
def but1():
img = Image.open("captain_scarlett.gif")
intro = ImageTk.PhotoImage(img)
right = Label(win, image=intro)
right.grid(row=0, column=1, rowspan=14)
right.image=intro

Related

Python Tkinter: Placing buttons in frame

I'm trying to create different frames and switch/destroy them so that you can move between windows like you would in a normal iOS app.
To do so, I need to place the widgets (components) in frames (containers).
However, when I try to add a button to the frame it doesn't pack it to the right side.
Here is my code:
from tkinter import *
root=Tk()
root.geometry('500x500')
root.title('Good morning :)')
frame1=Frame(root,width=500,height=500,bg='green')
frame1.pack()
button1=Button(frame1,text='Hello')
button1.pack(side='bottom')
You need to expand the Frame to fill the entire top-level window, and you need to tell the Button to pack on side='right' instead of side='bottom'.
And you need to run root.mainloop() at the end.
from tkinter import *
root = Tk()
root.geometry('500x500')
root.title('Good morning :)')
frame1 = Frame(root, bg='green')
frame1.pack(expand=True, fill=BOTH)
button1 = Button(frame1, text='Hello')
button1.pack(side=RIGHT)
root.mainloop()
Also, you don't need the dimensions in the Frame statement, since it will expand to the full 500x500 stated in the geometry with the extra keyword arguments passed to the pack() function. By default, the Frame is only going to be big enough to hold the widgets inside it, so it will only be as big as the Button, unless you tell it to expand to the full size of the top-level root widget.

Updating gWidgets elements in R

I'm having trouble updating graphical elements in R and I can't figure it out. I'd appreciate a little push.
I'm trying to make a simple GUI which is prepopulated with some options, but when a button is pressed the database is queried (the query is modified by the GUI), and the result needs to change what's available in the gcomboboxes and gtables. I'm frankly amazed at how simple it is to create such an excellent environment in R.
I don't believe I can modify the body of gcomboboxes or gtables once they're on screen (if I can, that's probably my preferred solution). I also don't believe I can destroy individual elements of a glayout, only the entire glayout. But how do I get it back in the right order?
# Small example for GUI element creation and destruction
if(!require("RGtk2")) {library("RGtk2")}
if(!require("digest")) {library("digest")}
if(!require("cairoDevice")) {library("cairoDevice")}
if(!require("gWidgets")) {library("gWidgets")}
if(!require("gWidgetsRGtk2")) {library("gWidgetsRGtk2")}
nw<-gwindow("Test",toolkit=guiToolkit("RGtk2"))
g<-ggroup(horizontal=FALSE,cont=nw)
t1<-glayout(container=g) # Header
t2<-glayout(container=g) # Dynamic middle
t3<-glayout(container=g) # Footer
t1[1,1]<-gcombobox(c("foo","bar"))
t1[1,2]<-gbutton("Update")
t2[1,1]<-gframe("",container=t2)
t2[2,1]<-gcombobox(c("violin","metal"))
t2[3,1]<-gtable(c("YoYoMa","Metallica"))
t3[1,1]<-glabel("Filler text",container=t3)
delete(g,t2) # Unable to delete t2[2,1] and t2[3,1]
t2<-glayout(container=g)
#t2[2,1]<-gcombobox(c("violin","metal","pop")) ### Nope...
#t2[3,1]<-gtable(c("YoYoMa","Metallica","UB40"))
#add(t2,gcombobox(c("violin","metal","pop"))) ### Nope...
#add(t2,gtable(c("YoYoMa","Metallica","UB40")))
All my added elements go below my footer text. How do I straighten it out so they go between the header and footer?
If I don't delete the glayout, it looks like I can modify the contents of the gcombobox, but the UI doesn't really reflect it. I can see new text when I click the arrow, but the selection no longer appears to change.
...
t2[2,1]<-gcombobox(c("text to remove","violin","metal"))
t2[3,1]<-gtable(c("YoYoMa","Metallica"))
t3[1,1]<-glabel("Filler text",container=t3)
t2[2,1]<-gcombobox(c("violin","metal","pop")) # "text to remove" remains selected regardless of user input
t2[3,1]<-gtable(c("YoYoMa","Metallica","UB40"))
It was a little frustrating, but this is working well for me. I'll leave this solution here in case anybody else has trouble.
# Small example for GUI element creation and destruction
if(!require("RGtk2")) {library("RGtk2")}
if(!require("digest")) {library("digest")}
if(!require("cairoDevice")) {library("cairoDevice")}
if(!require("gWidgets")) {library("gWidgets")}
if(!require("gWidgetsRGtk2")) {library("gWidgetsRGtk2")}
nw<-gwindow("Test",toolkit=guiToolkit("RGtk2"))
g<-ggroup(horizontal=FALSE,cont=nw)
t1<-glayout(container=g) # Header
t2<-glayout(container=g) # Dynamic middle
t3<-glayout(container=g) # Footer
t1[1,1]<-gcombobox(c("foo","bar"))
t1[1,2]<-gbutton("Update")
t2[1,1]<-gframe("",container=t2)
t2[2,1]<-gcombobox(c("text to remove","violin","metal"))
t2[3,1]<-gtable(c("YoYoMa","Metallica"))
t2[3,1]<-gtable(BandList)
t3[1,1]<-glabel("Filler text",container=t3)
t2[2,1][]<-c("violin","metal","pop")
svalue(t2[2,1])<-"pop" #otherwise it's confused about defaults
t2[3,1][]<-c("YoYoMa","Metallica","UB40")
I found a way to edit the contents already on screen without needing to delete the screen elements.
# Small example for GUI element creation and destruction
if(!require("RGtk2")) {library("RGtk2")}
if(!require("digest")) {library("digest")}
if(!require("cairoDevice")) {library("cairoDevice")}
if(!require("gWidgets")) {library("gWidgets")}
if(!require("gWidgetsRGtk2")) {library("gWidgetsRGtk2")}
nw<-gwindow("Test",toolkit=guiToolkit("RGtk2"))
g<-ggroup(horizontal=FALSE,cont=nw)
t1<-glayout(container=g) # Header
t2<-glayout(container=g) # Dynamic middle
t3<-glayout(container=g) # Footer
t1[1,1]<-gcombobox(c("foo","bar"))
t1[1,2]<-gbutton("Update")
t2[1,1]<-gframe("",container=t2)
t2[2,1]<-gcombobox(c("text to remove","violin","metal"))
t2[3,1]<-gtable(c("YoYoMa","Metallica"))
t2[3,1]<-gtable(BandList)
t3[1,1]<-glabel("Filler text",container=t3)
t2[2,1][]<-c("violin","metal","pop")
svalue(t2[2,1])<-"pop" #otherwise it's confused about defaults
t2[3,1][]<-c("YoYoMa","Metallica","UB40")

phpexcel select cell after freezePane()

A) I would like to have a PHPExcel-generated file to open with cell A1 selected. Not a problem: I can do that.
B) I would like to have a PHPExcel-generated file with frozen panes (at 'E6', but that's not the real issue). Again, not a problem: I can do that.
Now, when trying to do A and B, that's when I hit a real problem: the file always opens with cell E6 selected, no matter what I try...
I've tried using
$objPHPExcel->getActiveSheet()->freezePane('E6');
in different stages of the file construction (right at the beginning, at the end, in the middle), always with
$objPHPExcel->getActiveSheet()->setSelectedCell('A1');
AFTER freezing the panes, but no luck...
I searched and searched and found no solution to this (except a perhaps-related-but-unanswered request here at SO). Either I'm overlooking something obviously simple or I've uncovered a small bug... :-) Can someone help?
Many thanks in anticipation.
Looking at the code, The Excel2007 Writer overrides the selected cell when there's a split pane, changing it to the top-left cell of the split.
Quick and dirty fix in Classes/PHPExcel/Writer/Excel2007/Worksheet.php, change line 262 which should read
$activeCell = $topLeftCell;
to
$activeCell = empty($activeCell) ? $topLeftCell : $activeCell;
I haven't tested it fully, but it should work for now.... I really should be testing to see which "pane" the selected cell falls into, and setting appropriately in that pane

How to close a window when you click a button to open another window

I am working on a program that will allow someone to enter details in order to write a CV. I am using the Tkinter module (as extra practice) but am already stuck on the menu!
At the moment I have three different options the user can choose: Write CV, Review CV and Exit. I have created a button for each option and when the user presses the button it'll open, however the menu window remains open (there is a different subroutine for each option).
I understand that you need to do something like window.destroy(), however I'm not sure how to give a button two commands without doing something too fiddly like create more subroutines etc.?
The other option I think I'd prefer is is I could clear the menu screen?
Here is the programming I have at the moment:
def Main_Menu():
import tkinter
main_menu = tkinter.Tk()
main_menu.title("CV Writer")
main_menu.geometry("300x300")
main_menu.wm_iconbitmap('cv_icon.ico')
title = tkinter.Label(main_menu, text = "Main Menu", font=("Helvetica",25))
title.pack()
gap = tkinter.Label(main_menu, text = "")
gap.pack()
write_cv = tkinter.Button(main_menu, text = "1) Write CV", font=("Helvetica"), command=Write_CV)
write_cv.pack()
review_cv = tkinter.Button(main_menu, text = "2) Review CV", font=("Helvetica"), command=Review_CV)
review_cv.pack()
leave = tkinter.Button(main_menu, text = "3) Exit", font=("Helvetica"), command=Exit)
leave.pack()
main_menu.mainloop()
def Write_CV():
import tkinter
write_cv = tkinter.Tk()
write_cv.geometry("300x300")
write_cv.title("Write CV")
def Review_CV():
import tkinter
review_cv = tkinter.Tk()
review_cv.geometry("300x300")
review_cv.title("Review CV")
def Exit():
import tkinter
leave = tkinter.Tk()
leave.geometry("300x300")
leave.title("Exit")
Main_Menu()
Running the program should help make this question make more sense!
I am so sorry for the wordy question, but any kind of help would be appreciated! Please bear in mind I am only a GCSE student so simple language would also be so nice! Thank you!
I don't know why are you importing tkinter under each method, it's completely useless. Simply import it once at the beginning of your file with a syntax like this:
import tkinter as tk
So that you can refer to the widgets simply with the duo tk:
btn = tk.Button(None, text='I can simply refer to a widget with tk')
Apart from this, the structure of your program is really bad. In my opinion, you should not instantiate Tk inside your function Main_Menu, because it will only be visible inside it. If you want to refer to the master or root or whatever you want to call the instance of Tk, you can't, because it's a local instance, as I said above.
I usually instantiate Tk in the main function of my program, or in the following if __name__ == '__main__': construct:
if __name__ == '__main__':
master = tk.Tk() # note I am using "tk"
# create your objects or call your functions here
master.mainloop()
Your are creating an instance of Tkin each of your function, that is really a bad practice, never do that. You should only create one instance of Tk for each Tkinter application.
You should use the object-oriented paradigm or make all your widgets global to structure your application.
Except these details, you can simply call master.destroy() when you want to destroy your main window and all its children widgets, where master is the Tk instance.
In general, you have a lot of errors and bad practices. My advice is:
Read a tutorial on Python first and then on Tkinter, before
proceeding.

Using PyQt and Qt4, is this the proper way to get a throbber in a QTabWidget tab?

I have some code creating a QTabWidget from Python using PyQt4. I want to get a 'throbber' animated gif in the tab. The /only way/ I have found how to do this is the following convoluted method.
tabBar = self.tabReports.tabBar()
lbl = QtGui.QLabel(self.tabReports)
movie = QtGui.QMovie(os.path.join(self.basedir, "images\\throbber.gif"))
lbl.setMovie(movie)
QtCore.QObject.connect(movie, QtCore.SIGNAL("frameChanged(int)"), lambda i: movie.jumpToFrame(i))
movie.start()
log.debug("valid = %s"%(movie.isValid()))
tabBar.setTabButton(idxtab, QtGui.QTabBar.LeftSide, lbl)
The debugging call always returns true, but the throbber sometimes works, sometimes is blank, and sometimes has a large ugly delay between frames. In particular, I can't help but think connecting the frameChanged signal from the movie to a function that simply calls jumpToFrame on the same movie is not correct.
Even more distressing, if I simply drop the lambda (That is, make the line say QtCore.QObject.connect(movie, QtCore.SIGNAL("frameChanged(int)"), movie.jumpToFrame) it never renders even the first frame.
So, what am I doing wrong?
PS: I realize .tabBar() is a protected member, but I assumed (apparently correctly) that PyQt unprotects protected members :). I'm new to Qt, and i'd rather not subclass QTabWidget if I can help it.
I believe the problem with the code I initially posted was that the QMovie didn't have a parent, and thus scoping issues allowed the underlying C++ issue to be destroyed. It is also possible I had had threading issues - threading.thread and QThread do not play nice together. The working code I have now is below - no messing with signals nor slots needed.
def animateTab(self, tab_widget, enable):
tw = tab_widget
tabBar = tw.tabBar()
if enable:
lbl = QtGui.QLabel(tw)
movie = QtGui.QMovie("images\\throbber.gif"), parent=lbl)
movie.setScaledSize(QtCore.QSize(16, 16))
lbl.setMovie(movie)
movie.start()
else:
lbl = QtGui.QLabel(tw)
lbl.setMinimumSize(QtCore.QSize(16, 16))
tabBar.setTabButton(tab_section.index, QtGui.QTabBar.LeftSide, lbl)
I faced the same problem and this posting helped to make it work:
http://www.daniweb.com/forums/printthread.php?t=191210&pp=40
For me this seems to make the difference: QMovie("image.gif", QByteArray(), self)

Resources