python的图形化界面(1)

时间:2022-01-21 06:27:20

今天学习了python的图形化界面。

遇到的问题,就是导入Tklinter类的时候,出现了错误,提示说模块不存在,但是最后在文件的头部添加一行代码之后解决:

#! /usr/bin/env python

  先创建一个空的界面窗口吧:

#! /usr/bin/env python
#coding=utf-8
from Tkinter import *

class LabelDemo( Frame ):
   """Demonstrate Labels"""
   
   def __init__( self ):
      """Create three Labels and pack them"""
      
      Frame.__init__( self )   # initializes Frame instance

    
def main():
   LabelDemo().mainloop()  # starts event loop

if __name__ == "__main__":
   main()

  默认的窗口什么都没有,很丑。

然后先添加几个标签玩玩吧:

#! /usr/bin/env python
#coding=utf-8
from Tkinter import *

class LabelDemo( Frame ):
   """Demonstrate Labels"""
   
   def __init__( self ):
      """Create three Labels and pack them"""
      
      Frame.__init__( self )   # initializes Frame instance

      # frame fills all available space
      self.pack( expand = YES, fill = BOTH )
      self.master.title( "Labels" )

      self.Label1 = Label( self, text = "Label with text" )

      # resize frame to accommodate Label
      self.Label1.pack()

      self.Label2 = Label( self,
         text = "Labels with text and a bitmap" )

      # insert Label against left side of frame
      self.Label2.pack( side = LEFT )

      # using default bitmap image as label
      self.Label3 = Label( self, bitmap = "warning" )
      self.Label3.pack( side = LEFT )

def main():
   LabelDemo().mainloop()  # starts event loop

if __name__ == "__main__":
   main()

  注意一下,添加组件的时候,下面这一行代码还是不能少的,笔者也是刚刚接触,说错了大家别喷。

self.pack()

  如果取消这一行的话,其他的组件不能显示。